package com.lnw.controller;

import com.lnw.entity.Result;
import com.lnw.entity.User;
import com.lnw.service.UserService;
import com.lnw.utils.CreateImageCode;
import com.lnw.utils.ValidateImageCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.Base64Utils;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.security.PublicKey;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("user")
@CrossOrigin//允许跨域
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 生成验证码
     *
     * @param
     * @param request
     * @throws IOException
     */
    @GetMapping("getImage")

    public Map<String,String> getImage(HttpServletRequest request) throws IOException {
        Map<String,String> result = new HashMap<>();
        CreateImageCode imageCode = new CreateImageCode();
        //获取验证码
        String securityCode = imageCode.getCode();
        //验证码存入session
        String key = new SimpleDateFormat("yyyyMMddHH:mm:ss").format(new Date());
        request.getServletContext().setAttribute(key,securityCode);
        //session.setAttribute("code", securityCode);
        //生成图片
        BufferedImage image = imageCode.getBuffImg();
        //进行base64编码
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ImageIO.write(image, "png", bos);
        String string = Base64Utils.encodeToString(bos.toByteArray());
        result.put("key",key);
        result.put("image",string);
        return result;

    }

    /**
     * 用户注册
     *
     * @param code
     * @param user
     * @return
     */
    @PostMapping("register")
    public Result register(String code, String key,@RequestBody User user, HttpServletRequest request) {
        Result result = new Result();
        /*log.info("接收的验证码：" + code);
        log.info("接收用户：" + user);*/
        //验证验证码
        String keyCode = (String) request.getServletContext().getAttribute(key);
        //log.info(keyCode);
        try {
            if (code.equalsIgnoreCase(keyCode)) {
                //注册用户
                userService.register(user);
                result.setMsg("注册成功");
            } else {
                throw new RuntimeException("验证码错误！");
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.setMsg(e.getMessage()).setStatus(false);

        }
        return result;

    }

    @RequestMapping("login")
    public Result login(@RequestBody User user,HttpServletRequest request){
        Result result = new Result();
        log.info("user数据"+user);
        try{
            User login = userService.login(user);
            //登录成功，保存用户标记
            request.getServletContext().setAttribute(login.getId(),login);
            result.setMsg("登录成功").setUserId(login.getId());
        }catch (Exception e){
            e.printStackTrace();
            result.setStatus(false).setMsg(e.getMessage());
        }
        return  result;

    }

    /**
     * 查询单个用户
     * @param id
     * @return
     */
    @GetMapping("findOne")
    public User findOne(String id){
      return   userService.findByUserId(id);
    }
}
